home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / xulrunner-1.9.1.5 / components / nsHelperAppDlg.js < prev    next >
Text File  |  2009-11-09  |  42KB  |  1,040 lines

  1. /*
  2. //@line 45 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  3. */
  4.  
  5. /* This file implements the nsIHelperAppLauncherDialog interface.
  6.  *
  7.  * The implementation consists of a JavaScript "class" named nsUnknownContentTypeDialog,
  8.  * comprised of:
  9.  *   - a JS constructor function
  10.  *   - a prototype providing all the interface methods and implementation stuff
  11.  *
  12.  * In addition, this file implements an nsIModule object that registers the
  13.  * nsUnknownContentTypeDialog component.
  14.  */
  15.  
  16. const PREF_BD_USEDOWNLOADDIR = "browser.download.useDownloadDir";
  17. const nsITimer = Components.interfaces.nsITimer;
  18.  
  19. Components.utils.import("resource://gre/modules/DownloadLastDir.jsm");
  20.  
  21. /* ctor
  22.  */
  23. function nsUnknownContentTypeDialog() {
  24.     // Initialize data properties.
  25.     this.mLauncher = null;
  26.     this.mContext  = null;
  27.     this.mSourcePath = null;
  28.     this.chosenApp = null;
  29.     this.givenDefaultApp = false;
  30.     this.updateSelf = true;
  31.     this.mTitle    = "";
  32. }
  33.  
  34. nsUnknownContentTypeDialog.prototype = {
  35.     nsIMIMEInfo  : Components.interfaces.nsIMIMEInfo,
  36.  
  37.     QueryInterface: function (iid) {
  38.         if (!iid.equals(Components.interfaces.nsIHelperAppLauncherDialog) &&
  39.             !iid.equals(Components.interfaces.nsITimerCallback) &&
  40.             !iid.equals(Components.interfaces.nsISupports)) {
  41.             throw Components.results.NS_ERROR_NO_INTERFACE;
  42.         }
  43.         return this;
  44.     },
  45.  
  46.     // ---------- nsIHelperAppLauncherDialog methods ----------
  47.  
  48.     // show: Open XUL dialog using window watcher.  Since the dialog is not
  49.     //       modal, it needs to be a top level window and the way to open
  50.     //       one of those is via that route).
  51.     show: function(aLauncher, aContext, aReason)  {
  52.       this.mLauncher = aLauncher;
  53.       this.mContext  = aContext;
  54.  
  55.       const nsITimer = Components.interfaces.nsITimer;
  56.       this._showTimer = Components.classes["@mozilla.org/timer;1"]
  57.                                   .createInstance(nsITimer);
  58.       this._showTimer.initWithCallback(this, 0, nsITimer.TYPE_ONE_SHOT);
  59.     },
  60.  
  61.     // When opening from new tab, if tab closes while dialog is opening,
  62.     // (which is a race condition on the XUL file being cached and the timer
  63.     // in nsExternalHelperAppService), the dialog gets a blur and doesn't
  64.     // activate the OK button.  So we wait a bit before doing opening it.
  65.     reallyShow: function() {
  66.         try {
  67.           var ir = this.mContext.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  68.           var dwi = ir.getInterface(Components.interfaces.nsIDOMWindowInternal);
  69.           var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  70.                              .getService(Components.interfaces.nsIWindowWatcher);
  71.           this.mDialog = ww.openWindow(dwi,
  72.                                        "chrome://mozapps/content/downloads/unknownContentType.xul",
  73.                                        null,
  74.                                        "chrome,centerscreen,titlebar,dialog=yes,dependent",
  75.                                        null);
  76.         } catch (ex) {
  77.           // The containing window may have gone away.  Break reference
  78.           // cycles and stop doing the download.
  79.           const NS_BINDING_ABORTED = 0x804b0002;
  80.           this.mLauncher.cancel(NS_BINDING_ABORTED);
  81.           return;
  82.         }
  83.  
  84.         // Hook this object to the dialog.
  85.         this.mDialog.dialog = this;
  86.  
  87.         // Hook up utility functions.
  88.         this.getSpecialFolderKey = this.mDialog.getSpecialFolderKey;
  89.  
  90.         // Watch for error notifications.
  91.         this.progressListener.helperAppDlg = this;
  92.         this.mLauncher.setWebProgressListener(this.progressListener);
  93.     },
  94.  
  95.     // promptForSaveToFile:  Display file picker dialog and return selected file.
  96.     //                       This is called by the External Helper App Service
  97.     //                       after the ucth dialog calls |saveToDisk| with a null
  98.     //                       target filename (no target, therefore user must pick).
  99.     //
  100.     //                       Alternatively, if the user has selected to have all
  101.     //                       files download to a specific location, return that
  102.     //                       location and don't ask via the dialog. 
  103.     //
  104.     // Note - this function is called without a dialog, so it cannot access any part
  105.     // of the dialog XUL as other functions on this object do. 
  106.     promptForSaveToFile: function(aLauncher, aContext, aDefaultFile, aSuggestedFileExtension, aForcePrompt) {
  107.       var result = null;
  108.       
  109.       this.mLauncher = aLauncher;
  110.  
  111.       let prefs = Components.classes["@mozilla.org/preferences-service;1"]
  112.                             .getService(Components.interfaces.nsIPrefBranch);
  113.  
  114.       if (!aForcePrompt) {
  115.         // Check to see if the user wishes to auto save to the default download
  116.         // folder without prompting. Note that preference might not be set.
  117.         let autodownload = false;
  118.         try {
  119.           autodownload = prefs.getBoolPref(PREF_BD_USEDOWNLOADDIR);
  120.         } catch (e) { }
  121.       
  122.         if (autodownload) {
  123.           // Retrieve the user's default download directory
  124.           let dnldMgr = Components.classes["@mozilla.org/download-manager;1"]
  125.                                   .getService(Components.interfaces.nsIDownloadManager);
  126.           let defaultFolder = dnldMgr.userDownloadsDirectory;
  127.           result = this.validateLeafName(defaultFolder, aDefaultFile, aSuggestedFileExtension);
  128.  
  129.           // Check to make sure we have a valid directory, otherwise, prompt
  130.           if (result)
  131.             return result;
  132.         }
  133.       }
  134.       
  135.       // Use file picker to show dialog.
  136.       var nsIFilePicker = Components.interfaces.nsIFilePicker;
  137.       var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  138.  
  139.       var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  140.       bundle = bundle.createBundle("chrome://mozapps/locale/downloads/unknownContentType.properties");
  141.  
  142.       var windowTitle = bundle.GetStringFromName("saveDialogTitle");
  143.       var parent = aContext.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindowInternal);
  144.       picker.init(parent, windowTitle, nsIFilePicker.modeSave);
  145.       picker.defaultString = aDefaultFile;
  146.  
  147.       if (aSuggestedFileExtension) {
  148.         // aSuggestedFileExtension includes the period, so strip it
  149.         picker.defaultExtension = aSuggestedFileExtension.substring(1);
  150.       } 
  151.       else {
  152.         try {
  153.           picker.defaultExtension = this.mLauncher.MIMEInfo.primaryExtension;
  154.         } 
  155.         catch (ex) { }
  156.       }
  157.  
  158.       var wildCardExtension = "*";
  159.       if (aSuggestedFileExtension) {
  160.         wildCardExtension += aSuggestedFileExtension;
  161.         picker.appendFilter(this.mLauncher.MIMEInfo.description, wildCardExtension);
  162.       }
  163.  
  164.       picker.appendFilters( nsIFilePicker.filterAll );
  165.  
  166.       var inPrivateBrowsing = false;
  167.       try {
  168.         var pbs = Components.classes["@mozilla.org/privatebrowsing;1"]
  169.                             .getService(Components.interfaces.nsIPrivateBrowsingService);
  170.         inPrivateBrowsing = pbs.privateBrowsingEnabled;
  171.       }
  172.       catch (e) {
  173.       }
  174.  
  175.       // Default to lastDir if it's valid, use the user's default
  176.       // downloads directory otherwise.
  177.       var dnldMgr = Components.classes["@mozilla.org/download-manager;1"]
  178.                               .getService(Components.interfaces.nsIDownloadManager);
  179.       try {
  180.         var lastDir;
  181.         if (inPrivateBrowsing && gDownloadLastDir.file)
  182.           lastDir = gDownloadLastDir.file;
  183.         else
  184.           lastDir = prefs.getComplexValue("browser.download.lastDir",
  185.                           Components.interfaces.nsILocalFile);
  186.         if (lastDir.exists())
  187.           picker.displayDirectory = lastDir;
  188.         else
  189.           picker.displayDirectory = dnldMgr.userDownloadsDirectory;
  190.       } catch (ex) {
  191.         picker.displayDirectory = dnldMgr.userDownloadsDirectory;
  192.       }
  193.  
  194.       if (picker.show() == nsIFilePicker.returnCancel) {
  195.         // null result means user cancelled.
  196.         return null;
  197.       }
  198.  
  199.       // Be sure to save the directory the user chose through the Save As... 
  200.       // dialog  as the new browser.download.dir since the old one
  201.       // didn't exist.
  202.       result = picker.file;
  203.  
  204.       if (result) {
  205.         try {
  206.           // Remove the file so that it's not there when we ensure non-existence later;
  207.           // this is safe because for the file to exist, the user would have had to
  208.           // confirm that he wanted the file overwritten.
  209.           if (result.exists())
  210.             result.remove(false);
  211.         }
  212.         catch (e) { }
  213.         var newDir = result.parent.QueryInterface(Components.interfaces.nsILocalFile);
  214.  
  215.         // Do not store the last save directory as a pref inside the private browsing mode
  216.         if (inPrivateBrowsing)
  217.           gDownloadLastDir.file = newDir;
  218.         else
  219.           prefs.setComplexValue("browser.download.lastDir", Components.interfaces.nsILocalFile, newDir);
  220.  
  221.         result = this.validateLeafName(newDir, result.leafName, null);
  222.       }
  223.       return result;
  224.     },
  225.  
  226.     /**
  227.      * Ensures that a local folder/file combination does not already exist in
  228.      * the file system (or finds such a combination with a reasonably similar
  229.      * leaf name), creates the corresponding file, and returns it.
  230.      *
  231.      * @param   aLocalFile
  232.      *          the folder where the file resides
  233.      * @param   aLeafName
  234.      *          the string name of the file (may be empty if no name is known,
  235.      *          in which case a name will be chosen)
  236.      * @param   aFileExt
  237.      *          the extension of the file, if one is known; this will be ignored
  238.      *          if aLeafName is non-empty
  239.      * @returns nsILocalFile
  240.      *          the created file
  241.      */
  242.     validateLeafName: function (aLocalFile, aLeafName, aFileExt)
  243.     {
  244.       if (!aLocalFile || !aLocalFile.exists())
  245.         return null;
  246.  
  247.       // Remove any leading periods, since we don't want to save hidden files
  248.       // automatically.
  249.       aLeafName = aLeafName.replace(/^\.+/, "");
  250.  
  251.       if (aLeafName == "")
  252.         aLeafName = "unnamed" + (aFileExt ? "." + aFileExt : "");
  253.       aLocalFile.append(aLeafName);
  254.  
  255.       this.makeFileUnique(aLocalFile);
  256.  
  257. //@line 318 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  258.  
  259.       return aLocalFile;
  260.     },
  261.  
  262.     /**
  263.      * Generates and returns a uniquely-named file from aLocalFile.  If
  264.      * aLocalFile does not exist, it will be the file returned; otherwise, a
  265.      * file whose name is similar to that of aLocalFile will be returned.
  266.      */
  267.     makeFileUnique: function (aLocalFile)
  268.     {
  269.       try {
  270.         // Note - this code is identical to that in 
  271.         //   toolkit/content/contentAreaUtils.js.
  272.         // If you are updating this code, update that code too! We can't share code
  273.         // here since this is called in a js component. 
  274.         var collisionCount = 0;
  275.         while (aLocalFile.exists()) {
  276.           collisionCount++;
  277.           if (collisionCount == 1) {
  278.             // Append "(2)" before the last dot in (or at the end of) the filename
  279.             // special case .ext.gz etc files so we don't wind up with .tar(2).gz
  280.             if (aLocalFile.leafName.match(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i)) {
  281.               aLocalFile.leafName = aLocalFile.leafName.replace(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i, "(2)$&");
  282.             }
  283.             else {
  284.               aLocalFile.leafName = aLocalFile.leafName.replace(/(\.[^\.]*)?$/, "(2)$&");
  285.             }
  286.           }
  287.           else {
  288.             // replace the last (n) in the filename with (n+1)
  289.             aLocalFile.leafName = aLocalFile.leafName.replace(/^(.*\()\d+\)/, "$1" + (collisionCount+1) + ")");
  290.           }
  291.         }
  292.         aLocalFile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  293.       }
  294.       catch (e) {
  295.         dump("*** exception in validateLeafName: " + e + "\n");
  296.         if (aLocalFile.leafName == "" || aLocalFile.isDirectory()) {
  297.           aLocalFile.append("unnamed");
  298.           if (aLocalFile.exists())
  299.             aLocalFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  300.         }
  301.       }
  302.     },
  303.     
  304.     // ---------- implementation methods ----------
  305.  
  306.     // Web progress listener so we can detect errors while mLauncher is
  307.     // streaming the data to a temporary file.
  308.     progressListener: {
  309.         // Implementation properties.
  310.         helperAppDlg: null,
  311.  
  312.         // nsIWebProgressListener methods.
  313.         // Look for error notifications and display alert to user.
  314.         onStatusChange: function( aWebProgress, aRequest, aStatus, aMessage ) {
  315.             if ( aStatus != Components.results.NS_OK ) {
  316.                 // Get prompt service.
  317.                 var prompter = Components.classes[ "@mozilla.org/embedcomp/prompt-service;1" ]
  318.                                    .getService( Components.interfaces.nsIPromptService );
  319.                 // Display error alert (using text supplied by back-end).
  320.                 prompter.alert( this.dialog, this.helperAppDlg.mTitle, aMessage );
  321.  
  322.                 // Close the dialog.
  323.                 this.helperAppDlg.onCancel();
  324.                 if ( this.helperAppDlg.mDialog ) {
  325.                     this.helperAppDlg.mDialog.close();
  326.                 }
  327.             }
  328.         },
  329.  
  330.         // Ignore onProgressChange, onProgressChange64, onStateChange, onLocationChange, onSecurityChange, and onRefreshAttempted notifications.
  331.         onProgressChange: function( aWebProgress,
  332.                                     aRequest,
  333.                                     aCurSelfProgress,
  334.                                     aMaxSelfProgress,
  335.                                     aCurTotalProgress,
  336.                                     aMaxTotalProgress ) {
  337.         },
  338.  
  339.         onProgressChange64: function( aWebProgress,
  340.                                       aRequest,
  341.                                       aCurSelfProgress,
  342.                                       aMaxSelfProgress,
  343.                                       aCurTotalProgress,
  344.                                       aMaxTotalProgress ) {
  345.         },
  346.  
  347.  
  348.  
  349.         onStateChange: function( aWebProgress, aRequest, aStateFlags, aStatus ) {
  350.         },
  351.  
  352.         onLocationChange: function( aWebProgress, aRequest, aLocation ) {
  353.         },
  354.  
  355.         onSecurityChange: function( aWebProgress, aRequest, state ) {
  356.         },
  357.  
  358.         onRefreshAttempted: function( aWebProgress, aURI, aDelay, aSameURI ) {
  359.           return true;
  360.     }
  361.     },
  362.  
  363.     // initDialog:  Fill various dialog fields with initial content.
  364.     initDialog : function() {
  365.       // Put file name in window title.
  366.       var suggestedFileName = this.mLauncher.suggestedFileName;
  367.  
  368.       // Some URIs do not implement nsIURL, so we can't just QI.
  369.       var url   = this.mLauncher.source;
  370.       var fname = "";
  371.       this.mSourcePath = url.prePath;
  372.       try {
  373.           url = url.QueryInterface( Components.interfaces.nsIURL );
  374.           // A url, use file name from it.
  375.           fname = url.fileName;
  376.           this.mSourcePath += url.directory;
  377.       } catch (ex) {
  378.           // A generic uri, use path.
  379.           fname = url.path;
  380.           this.mSourcePath += url.path;
  381.       }
  382.  
  383.       if (suggestedFileName)
  384.         fname = suggestedFileName;
  385.       
  386.       var displayName = fname.replace(/ +/g, " ");
  387.  
  388.       this.mTitle = this.dialogElement("strings").getFormattedString("title", [displayName]);
  389.       this.mDialog.document.title = this.mTitle;
  390.  
  391.       // Put content type, filename and location into intro.
  392.       this.initIntro(url, fname, displayName);
  393.  
  394.       var iconString = "moz-icon://" + fname + "?size=16&contentType=" + this.mLauncher.MIMEInfo.MIMEType;
  395.       this.dialogElement("contentTypeImage").setAttribute("src", iconString);
  396.  
  397.       // if always-save and is-executable and no-handler
  398.       // then set up simple ui
  399.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  400.       var shouldntRememberChoice = (mimeType == "application/octet-stream" || 
  401.                                     mimeType == "application/x-msdownload" ||
  402.                                     this.mLauncher.targetFileIsExecutable);
  403.       if (shouldntRememberChoice && !this.openWithDefaultOK()) {
  404.         // hide featured choice 
  405.         this.dialogElement("normalBox").collapsed = true;
  406.         // show basic choice 
  407.         this.dialogElement("basicBox").collapsed = false;
  408.         // change button labels and icons; use "save" icon for the accept
  409.         // button since it's the only action possible
  410.         let acceptButton = this.mDialog.document.documentElement
  411.                                .getButton("accept");
  412.         acceptButton.label = this.dialogElement("strings")
  413.                                  .getString("unknownAccept.label");
  414.         acceptButton.setAttribute("icon", "save");
  415.         this.mDialog.document.documentElement.getButton("cancel").label = this.dialogElement("strings").getString("unknownCancel.label");
  416.         // hide other handler
  417.         this.dialogElement("openHandler").collapsed = true;
  418.         // set save as the selected option
  419.         this.dialogElement("mode").selectedItem = this.dialogElement("save");
  420.       }
  421.       else {
  422.         this.initAppAndSaveToDiskValues();
  423.  
  424.         // Initialize "always ask me" box. This should always be disabled
  425.         // and set to true for the ambiguous type application/octet-stream.
  426.         // We don't also check for application/x-msdownload here since we
  427.         // want users to be able to autodownload .exe files. 
  428.         var rememberChoice = this.dialogElement("rememberChoice");
  429.  
  430. //@line 509 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  431.         if (shouldntRememberChoice) {
  432.           rememberChoice.checked = false;
  433.           rememberChoice.disabled = true;
  434.         }
  435.         else {
  436.           rememberChoice.checked = !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  437.         }
  438.         this.toggleRememberChoice(rememberChoice);
  439.  
  440.         // XXXben - menulist won't init properly, hack. 
  441.         var openHandler = this.dialogElement("openHandler");
  442.         openHandler.parentNode.removeChild(openHandler);
  443.         var openHandlerBox = this.dialogElement("openHandlerBox");
  444.         openHandlerBox.appendChild(openHandler);
  445.       }
  446.  
  447.       this.mDialog.setTimeout("dialog.postShowCallback()", 0);
  448.       
  449.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  450.       this._showTimer = Components.classes["@mozilla.org/timer;1"]
  451.                                   .createInstance(nsITimer);
  452.       this._showTimer.initWithCallback(this, 250, nsITimer.TYPE_ONE_SHOT);
  453.     },
  454.  
  455.     notify: function (aTimer) {
  456.       if (aTimer == this._showTimer) {
  457.         if (!this.mDialog) {
  458.           this.reallyShow();
  459.         } else {
  460.           // The user may have already canceled the dialog.
  461.           try {
  462.             if (!this._blurred) {
  463.               this.mDialog.document.documentElement.getButton("accept").disabled = false;
  464.             }
  465.           } catch (ex) {}
  466.           this._delayExpired = true;
  467.         }
  468.         // The timer won't release us, so we have to release it.
  469.         this._showTimer = null;
  470.       }
  471.       else if (aTimer == this._saveToDiskTimer) {
  472.         // Since saveToDisk may open a file picker and therefore block this routine,
  473.         // we should only call it once the dialog is closed.
  474.         this.mLauncher.saveToDisk(null, false);
  475.         this._saveToDiskTimer = null;
  476.       }
  477.     },
  478.  
  479.     postShowCallback: function () {
  480.       this.mDialog.sizeToContent();
  481.  
  482.       // Set initial focus
  483.       this.dialogElement("mode").focus();
  484.     },
  485.  
  486.     // initIntro:
  487.     initIntro: function(url, filename, displayname) {
  488.         this.dialogElement( "location" ).value = displayname;
  489.         this.dialogElement( "location" ).setAttribute("realname", filename);
  490.         this.dialogElement( "location" ).setAttribute("tooltiptext", displayname);
  491.  
  492.         // if mSourcePath is a local file, then let's use the pretty path name instead of an ugly
  493.         // url...
  494.         var pathString = this.mSourcePath;
  495.         try 
  496.         {
  497.           var fileURL = url.QueryInterface(Components.interfaces.nsIFileURL);
  498.           if (fileURL)
  499.           {
  500.             var fileObject = fileURL.file;
  501.             if (fileObject)
  502.             {
  503.               var parentObject = fileObject.parent;
  504.               if (parentObject)
  505.               {
  506.                 pathString = parentObject.path;
  507.               }
  508.             }
  509.           }
  510.         } catch(ex) {}
  511.  
  512.         if (pathString == this.mSourcePath)
  513.         {
  514.           // wasn't a fileURL
  515.           var tmpurl = url.clone(); // don't want to change the real url
  516.           try {
  517.             tmpurl.userPass = "";
  518.           } catch (ex) {}
  519.           pathString = tmpurl.prePath;
  520.         }
  521.  
  522.         // Set the location text, which is separate from the intro text so it can be cropped
  523.         var location = this.dialogElement( "source" );
  524.         location.value = pathString;
  525.         location.setAttribute("tooltiptext", this.mSourcePath);
  526.         
  527.         // Show the type of file. 
  528.         var type = this.dialogElement("type");
  529.         var mimeInfo = this.mLauncher.MIMEInfo;
  530.         
  531.         // 1. Try to use the pretty description of the type, if one is available.
  532.         var typeString = mimeInfo.description;
  533.         
  534.         if (typeString == "") {
  535.           // 2. If there is none, use the extension to identify the file, e.g. "ZIP file"
  536.           var primaryExtension = "";
  537.           try {
  538.             primaryExtension = mimeInfo.primaryExtension;
  539.           }
  540.           catch (ex) {
  541.           }
  542.           if (primaryExtension != "")
  543.             typeString = this.dialogElement("strings").getFormattedString("fileType", [primaryExtension.toUpperCase()]);
  544.           // 3. If we can't even do that, just give up and show the MIME type. 
  545.           else
  546.             typeString = mimeInfo.MIMEType;
  547.         }
  548.         
  549.         type.value = typeString;
  550.     },
  551.     
  552.     _blurred: false,
  553.     _delayExpired: false, 
  554.     onBlur: function(aEvent) {
  555.       this._blurred = true;
  556.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  557.     },
  558.     
  559.     onFocus: function(aEvent) {
  560.       this._blurred = false;
  561.       if (this._delayExpired) {
  562.         var script = "document.documentElement.getButton('accept').disabled = false";
  563.         this.mDialog.setTimeout(script, 250);
  564.       }
  565.     },
  566.  
  567.     // Returns true if opening the default application makes sense.
  568.     openWithDefaultOK: function() {
  569.         // The checking is different on Windows...
  570. //@line 659 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  571.             // On other platforms, default is Ok if there is a default app.
  572.             // Note that nsIMIMEInfo providers need to ensure that this holds true
  573.             // on each platform.
  574.         return this.mLauncher.MIMEInfo.hasDefaultHandler;
  575. //@line 664 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  576.     },
  577.     
  578.     // Set "default" application description field.
  579.     initDefaultApp: function() {
  580.       // Use description, if we can get one.
  581.       var desc = this.mLauncher.MIMEInfo.defaultDescription;
  582.       if (desc) {
  583.         var defaultApp = this.dialogElement("strings").getFormattedString("defaultApp", [desc]);
  584.         this.dialogElement("defaultHandler").label = defaultApp;
  585.       }
  586.       else {
  587.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "1");
  588.         // Hide the default handler item too, in case the user picks a 
  589.         // custom handler at a later date which triggers the menulist to show.
  590.         this.dialogElement("defaultHandler").hidden = true;
  591.       }
  592.     },
  593.  
  594.     // getPath:
  595.     getPath: function (aFile) {
  596. //@line 687 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  597.       return aFile.path;
  598. //@line 689 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  599.     },
  600.  
  601.     // initAppAndSaveToDiskValues:
  602.     initAppAndSaveToDiskValues: function() {
  603.       var modeGroup = this.dialogElement("mode");
  604.  
  605.       // We don't let users open .exe files or random binary data directly 
  606.       // from the browser at the moment because of security concerns. 
  607.       var openWithDefaultOK = this.openWithDefaultOK();
  608.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  609.       if (this.mLauncher.targetFileIsExecutable || (
  610.           (mimeType == "application/octet-stream" ||
  611.            mimeType == "application/x-msdownload") && 
  612.            !openWithDefaultOK)) {
  613.         this.dialogElement("open").disabled = true;
  614.         var openHandler = this.dialogElement("openHandler");
  615.         openHandler.disabled = true;
  616.         openHandler.selectedItem = null;
  617.         modeGroup.selectedItem = this.dialogElement("save");
  618.         return;
  619.       }
  620.     
  621.       // Fill in helper app info, if there is any.
  622.       try {
  623.         this.chosenApp =
  624.           this.mLauncher.MIMEInfo.preferredApplicationHandler
  625.               .QueryInterface(Components.interfaces.nsILocalHandlerApp);
  626.       } catch (e) {
  627.         this.chosenApp = null;
  628.       }
  629.       // Initialize "default application" field.
  630.       this.initDefaultApp();
  631.  
  632.       var otherHandler = this.dialogElement("otherHandler");
  633.               
  634.       // Fill application name textbox.
  635.       if (this.chosenApp && this.chosenApp.executable && 
  636.           this.chosenApp.executable.path) {
  637.         otherHandler.setAttribute("path",
  638.                                   this.getPath(this.chosenApp.executable));
  639.  
  640. //@line 734 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  641.         otherHandler.label = this.chosenApp.executable.leafName;
  642. //@line 736 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  643.         otherHandler.hidden = false;
  644.       }
  645.  
  646.       var useDefault = this.dialogElement("useSystemDefault");
  647.       var openHandler = this.dialogElement("openHandler");
  648.       openHandler.selectedIndex = 0;
  649.  
  650.       if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useSystemDefault) {
  651.         // Open (using system default).
  652.         modeGroup.selectedItem = this.dialogElement("open");
  653.       } else if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useHelperApp) {
  654.         // Open with given helper app.
  655.         modeGroup.selectedItem = this.dialogElement("open");
  656.         openHandler.selectedIndex = 1;
  657.       } else {
  658.         // Save to disk.
  659.         modeGroup.selectedItem = this.dialogElement("save");
  660.       }
  661.       
  662.       // If we don't have a "default app" then disable that choice.
  663.       if (!openWithDefaultOK) {
  664.         var useDefault = this.dialogElement("defaultHandler");
  665.         var isSelected = useDefault.selected;
  666.         
  667.         // Disable that choice.
  668.         useDefault.hidden = true;
  669.         // If that's the default, then switch to "save to disk."
  670.         if (isSelected) {
  671.           openHandler.selectedIndex = 1;
  672.           modeGroup.selectedItem = this.dialogElement("save");
  673.         }
  674.       }
  675.       
  676.       otherHandler.nextSibling.hidden = otherHandler.nextSibling.nextSibling.hidden = false;
  677.       this.updateOKButton();
  678.     },
  679.  
  680.     // Returns the user-selected application
  681.     helperAppChoice: function() {
  682.       return this.chosenApp;
  683.     },
  684.     
  685.     get saveToDisk() {
  686.       return this.dialogElement("save").selected;
  687.     },
  688.     
  689.     get useOtherHandler() {
  690.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 1;
  691.     },
  692.     
  693.     get useSystemDefault() {
  694.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 0;
  695.     },
  696.     
  697.     toggleRememberChoice: function (aCheckbox) {
  698.         this.dialogElement("settingsChange").hidden = !aCheckbox.checked;
  699.         this.mDialog.sizeToContent();
  700.     },
  701.     
  702.     openHandlerCommand: function () {
  703.       var openHandler = this.dialogElement("openHandler");
  704.       if (openHandler.selectedItem.id == "choose")
  705.         this.chooseApp();
  706.       else
  707.         openHandler.setAttribute("lastSelectedItemID", openHandler.selectedItem.id);
  708.     },
  709.  
  710.     updateOKButton: function() {
  711.       var ok = false;
  712.       if (this.dialogElement("save").selected) {
  713.         // This is always OK.
  714.         ok = true;
  715.       } 
  716.       else if (this.dialogElement("open").selected) {
  717.         switch (this.dialogElement("openHandler").selectedIndex) {
  718.         case 0:
  719.           // No app need be specified in this case.
  720.           ok = true;
  721.           break;
  722.         case 1:
  723.           // only enable the OK button if we have a default app to use or if 
  724.           // the user chose an app....
  725.           ok = this.chosenApp || /\S/.test(this.dialogElement("otherHandler").getAttribute("path")); 
  726.         break;
  727.         }
  728.       }
  729.  
  730.       // Enable Ok button if ok to press.
  731.       this.mDialog.document.documentElement.getButton("accept").disabled = !ok;
  732.     },
  733.     
  734.     // Returns true iff the user-specified helper app has been modified.
  735.     appChanged: function() {
  736.       return this.helperAppChoice() != this.mLauncher.MIMEInfo.preferredApplicationHandler;
  737.     },
  738.  
  739.     updateMIMEInfo: function() {
  740.       var needUpdate = false;
  741.       // If current selection differs from what's in the mime info object,
  742.       // then we need to update.
  743.       if (this.saveToDisk) {
  744.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.saveToDisk;
  745.         if (needUpdate)
  746.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.saveToDisk;
  747.       } 
  748.       else if (this.useSystemDefault) {
  749.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useSystemDefault;
  750.         if (needUpdate)
  751.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useSystemDefault;
  752.       } 
  753.       else {
  754.         // For "open with", we need to check both preferred action and whether the user chose
  755.         // a new app.
  756.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useHelperApp || this.appChanged();
  757.         if (needUpdate) {
  758.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useHelperApp;
  759.           // App may have changed - Update application
  760.           var app = this.helperAppChoice();
  761.           this.mLauncher.MIMEInfo.preferredApplicationHandler = app;
  762.         }
  763.       }
  764.       // We will also need to update if the "always ask" flag has changed.
  765.       needUpdate = needUpdate || this.mLauncher.MIMEInfo.alwaysAskBeforeHandling != (!this.dialogElement("rememberChoice").checked);
  766.  
  767.       // One last special case: If the input "always ask" flag was false, then we always
  768.       // update.  In that case we are displaying the helper app dialog for the first
  769.       // time for this mime type and we need to store the user's action in the mimeTypes.rdf
  770.       // data source (whether that action has changed or not; if it didn't change, then we need
  771.       // to store the "always ask" flag so the helper app dialog will or won't display
  772.       // next time, per the user's selection).
  773.       needUpdate = needUpdate || !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  774.  
  775.       // Make sure mime info has updated setting for the "always ask" flag.
  776.       this.mLauncher.MIMEInfo.alwaysAskBeforeHandling = !this.dialogElement("rememberChoice").checked;
  777.  
  778.       return needUpdate;        
  779.     },
  780.     
  781.     // See if the user changed things, and if so, update the
  782.     // mimeTypes.rdf entry for this mime type.
  783.     updateHelperAppPref: function() {
  784.       var ha = new this.mDialog.HelperApps();
  785.       ha.updateTypeInfo(this.mLauncher.MIMEInfo);
  786.       ha.destroy();
  787.     },
  788.     
  789.     // onOK:
  790.     onOK: function() {
  791.       // Verify typed app path, if necessary.
  792.       if (this.useOtherHandler) {
  793.         var helperApp = this.helperAppChoice();
  794.         if (!helperApp || !helperApp.executable ||
  795.             !helperApp.executable.exists()) {
  796.           // Show alert and try again.        
  797.           var bundle = this.dialogElement("strings");                    
  798.           var msg = bundle.getFormattedString("badApp", [this.dialogElement("otherHandler").path]);
  799.           var svc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  800.           svc.alert(this.mDialog, bundle.getString("badApp.title"), msg);
  801.  
  802.           // Disable the OK button.
  803.           this.mDialog.document.documentElement.getButton("accept").disabled = true;
  804.           this.dialogElement("mode").focus();          
  805.  
  806.           // Clear chosen application.
  807.           this.chosenApp = null;
  808.  
  809.           // Leave dialog up.
  810.           return false;
  811.         }
  812.       }
  813.         
  814.       // Remove our web progress listener (a progress dialog will be
  815.       // taking over).
  816.       this.mLauncher.setWebProgressListener(null);
  817.  
  818.       // saveToDisk and launchWithApplication can return errors in 
  819.       // certain circumstances (e.g. The user clicks cancel in the
  820.       // "Save to Disk" dialog. In those cases, we don't want to
  821.       // update the helper application preferences in the RDF file.
  822.       try {
  823.         var needUpdate = this.updateMIMEInfo();
  824.         
  825.         if (this.dialogElement("save").selected) {
  826.           // If we're using a default download location, create a path
  827.           // for the file to be saved to to pass to |saveToDisk| - otherwise
  828.           // we must ask the user to pick a save name.
  829.  
  830. //@line 937 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  831.  
  832.           // see @notify
  833.           // we cannot use opener's setTimeout, see bug 420405
  834.           this._saveToDiskTimer = Components.classes["@mozilla.org/timer;1"]
  835.                                             .createInstance(nsITimer);
  836.           this._saveToDiskTimer.initWithCallback(this, 0,
  837.                                                  nsITimer.TYPE_ONE_SHOT);
  838.         }
  839.         else
  840.           this.mLauncher.launchWithApplication(null, false);
  841.  
  842.         // Update user pref for this mime type (if necessary). We do not
  843.         // store anything in the mime type preferences for the ambiguous
  844.         // type application/octet-stream. We do NOT do this for 
  845.         // application/x-msdownload since we want users to be able to 
  846.         // autodownload these to disk. 
  847.         if (needUpdate && this.mLauncher.MIMEInfo.MIMEType != "application/octet-stream")
  848.           this.updateHelperAppPref();
  849.       } catch(e) { }
  850.  
  851.       // Unhook dialog from this object.
  852.       this.mDialog.dialog = null;
  853.  
  854.       // Close up dialog by returning true.
  855.       return true;
  856.     },
  857.  
  858.     // onCancel:
  859.     onCancel: function() {
  860.       // Remove our web progress listener.
  861.       this.mLauncher.setWebProgressListener(null);
  862.  
  863.       // Cancel app launcher.
  864.       try {
  865.         const NS_BINDING_ABORTED = 0x804b0002;
  866.         this.mLauncher.cancel(NS_BINDING_ABORTED);
  867.       } catch(exception) {
  868.       }
  869.  
  870.       // Unhook dialog from this object.
  871.       this.mDialog.dialog = null;
  872.  
  873.       // Close up dialog by returning true.
  874.       return true;
  875.     },
  876.  
  877.     // dialogElement:  Convenience. 
  878.     dialogElement: function(id) {
  879.       return this.mDialog.document.getElementById(id);
  880.     },
  881.  
  882.     // Retrieve the pretty description from the file
  883.     getFileDisplayName: function getFileDisplayName(file)
  884.     { 
  885. //@line 999 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  886.         return file.leafName;
  887.     },
  888.  
  889.     // chooseApp:  Open file picker and prompt user for application.
  890.     chooseApp: function() {
  891. //@line 1070 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  892.       var nsIFilePicker = Components.interfaces.nsIFilePicker;
  893.       var fp = Components.classes["@mozilla.org/filepicker;1"]
  894.                          .createInstance(nsIFilePicker);
  895.       fp.init(this.mDialog,
  896.               this.dialogElement("strings").getString("chooseAppFilePickerTitle"),
  897.               nsIFilePicker.modeOpen);
  898.  
  899.       fp.appendFilters(nsIFilePicker.filterApps);
  900.  
  901.       if (fp.show() == nsIFilePicker.returnOK && fp.file) {
  902.         // Show the "handler" menulist since we have a (user-specified) 
  903.         // application now.
  904.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "0");
  905.         
  906.         // Remember the file they chose to run.
  907.         var localHandlerApp = 
  908.           Components.classes["@mozilla.org/uriloader/local-handler-app;1"].
  909.           createInstance(Components.interfaces.nsILocalHandlerApp);
  910.         localHandlerApp.executable = fp.file;
  911.         this.chosenApp = localHandlerApp;
  912.         
  913.         // Update dialog.
  914.         var otherHandler = this.dialogElement("otherHandler");
  915.         otherHandler.removeAttribute("hidden");
  916.         otherHandler.setAttribute("path", this.getPath(this.chosenApp.executable));
  917. //@line 1100 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  918.         otherHandler.label = this.chosenApp.executable.leafName;
  919. //@line 1102 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  920.         this.dialogElement("openHandler").selectedIndex = 1;
  921.         this.dialogElement("openHandler").setAttribute("lastSelectedItemID", "otherHandler");
  922.         
  923.         this.dialogElement("mode").selectedItem = this.dialogElement("open");
  924.       }
  925.       else {
  926.         var openHandler = this.dialogElement("openHandler");
  927.         var lastSelectedID = openHandler.getAttribute("lastSelectedItemID");
  928.         if (!lastSelectedID)
  929.           lastSelectedID = "defaultHandler";
  930.         openHandler.selectedItem = this.dialogElement(lastSelectedID);
  931.       }
  932. //@line 1115 "/build/buildd/xulrunner-1.9.1-1.9.1.5+nobinonly/build-tree/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  933.     },
  934.  
  935.     // Turn this on to get debugging messages.
  936.     debug: false,
  937.  
  938.     // Dump text (if debug is on).
  939.     dump: function( text ) {
  940.         if ( this.debug ) {
  941.             dump( text ); 
  942.         }
  943.     },
  944.  
  945.     // dumpInfo:
  946.     doDebug: function() {
  947.         const nsIProgressDialog = Components.interfaces.nsIProgressDialog;
  948.         // Open new progress dialog.
  949.         var progress = Components.classes[ "@mozilla.org/progressdialog;1" ]
  950.                          .createInstance( nsIProgressDialog );
  951.         // Show it.
  952.         progress.open( this.mDialog );
  953.     },
  954.  
  955.     // dumpObj:
  956.     dumpObj: function( spec ) {
  957.          var val = "<undefined>";
  958.          try {
  959.              val = eval( "this."+spec ).toString();
  960.          } catch( exception ) {
  961.          }
  962.          this.dump( spec + "=" + val + "\n" );
  963.     },
  964.  
  965.     // dumpObjectProperties
  966.     dumpObjectProperties: function( desc, obj ) {
  967.          for( prop in obj ) {
  968.              this.dump( desc + "." + prop + "=" );
  969.              var val = "<undefined>";
  970.              try {
  971.                  val = obj[ prop ];
  972.              } catch ( exception ) {
  973.              }
  974.              this.dump( val + "\n" );
  975.          }
  976.     }
  977. }
  978.  
  979. // This Component's module implementation.  All the code below is used to get this
  980. // component registered and accessible via XPCOM.
  981. var module = {
  982.     firstTime: true,
  983.  
  984.     // registerSelf: Register this component.
  985.     registerSelf: function (compMgr, fileSpec, location, type) {
  986.         if (this.firstTime) {
  987.             this.firstTime = false;
  988.             throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  989.         }
  990.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  991.  
  992.         compMgr.registerFactoryLocation( this.cid,
  993.                                          "Unknown Content Type Dialog",
  994.                                          this.contractId,
  995.                                          fileSpec,
  996.                                          location,
  997.                                          type );
  998.     },
  999.  
  1000.     // getClassObject: Return this component's factory object.
  1001.     getClassObject: function (compMgr, cid, iid) {
  1002.         if (!cid.equals(this.cid)) {
  1003.             throw Components.results.NS_ERROR_NO_INTERFACE;
  1004.         }
  1005.  
  1006.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  1007.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  1008.         }
  1009.  
  1010.         return this.factory;
  1011.     },
  1012.  
  1013.     /* CID for this class */
  1014.     cid: Components.ID("{F68578EB-6EC2-4169-AE19-8C6243F0ABE1}"),
  1015.  
  1016.     /* Contract ID for this class */
  1017.     contractId: "@mozilla.org/helperapplauncherdialog;1",
  1018.  
  1019.     /* factory object */
  1020.     factory: {
  1021.         // createInstance: Return a new nsProgressDialog object.
  1022.         createInstance: function (outer, iid) {
  1023.             if (outer != null)
  1024.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  1025.  
  1026.             return (new nsUnknownContentTypeDialog()).QueryInterface(iid);
  1027.         }
  1028.     },
  1029.  
  1030.     // canUnload: n/a (returns true)
  1031.     canUnload: function(compMgr) {
  1032.         return true;
  1033.     }
  1034. };
  1035.  
  1036. // NSGetModule: Return the nsIModule object.
  1037. function NSGetModule(compMgr, fileSpec) {
  1038.     return module;
  1039. }
  1040.